package com.bootx.service.predict;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 方法二：加权时间衰减平均
 * 思路：越新的 round 权重越大，近几轮影响更明显。
 */
public class WeightedMeanPredictor {

    public List<Prediction> predict(List<RedPackageRound> rounds) {
        int windowSize = Math.min(10, rounds.size());
        int[] weights = new int[windowSize]; // 权重 1~10
        for (int i = 0; i < windowSize; i++) weights[i] = i + 1;

        Map<Integer, Double> sumAmount = new HashMap<>();
        Map<Integer, Double> sumTime = new HashMap<>();
        Map<Integer, Integer> sumWeight = new HashMap<>();

        for (int i = 0; i < windowSize; i++) {
            RedPackageRound round = rounds.get(rounds.size() - windowSize + i);
            int weight = weights[i];
            for (RedPackageItem item : round.items) {
                sumAmount.merge(item.order, item.amount * weight, Double::sum);
                sumTime.merge(item.order, item.openTime * 1.0 * weight, Double::sum);
                sumWeight.merge(item.order, weight, Integer::sum);
            }
        }

        List<Prediction> predictions = new ArrayList<>();
        for (int order = 1; order <= 10; order++) {
            double avgAmount = sumAmount.getOrDefault(order, 0.0) / sumWeight.getOrDefault(order, 1);
            int avgTime = (int) (sumTime.getOrDefault(order, 0.0) / sumWeight.getOrDefault(order, 1));
            predictions.add(new Prediction(order, avgAmount, avgTime));
        }

        return predictions;
    }
}
